<?php

namespace App\Http\Controllers\Manage;

use App\Model\Manage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Input;
//use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rules\In;
use Validator;
use App\Model\Article;
use App\Model\ArticleCategory;

class ArticleController extends Controller
{
    /**
     * @var int 数据表id
     */
    public $table_id = 5;

    /**
     * CaseController constructor.
     */
    public function __construct()
    {
        parent::__construct($this->table_id);

    }
    /**
     * 列表页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index() {
        #判断权限
        if($this->rule['view'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $obj = new Article;
        $check_time = Input::Get('check_time');
        $category = Input::get('category');
        $keyword = Input::get('keyword');
        $time = Input::get('create_time');
        $type = Input::get('type');
        $code = Input::get('code');

        if(Input::has('category') && Input::has('keyword')) {
            if(Input::get('category') === 'category_id') {
                $cate = ArticleCategory::select('id')->where('name','like',"%$keyword%")->get();
                $obj = $obj->whereIn('category_id',$cate);
            }
            elseif(Input::get('category') === 'create_user' || Input::get('category') === 'update_user') {
                $user = Manage::select('id')->where('username','like',"%$keyword%")->get();
                $obj = $obj->whereIn(Input::get('category'),$user);
            }
            else {
                $obj = $obj->where(Input::get('category'),'like',"%$keyword%");
            }
        }
        if(Input::has('check_time')) {
            $start_time = date("Y-m-d 00:00:00",strtotime(substr($time , 0 , 10)));
            $end_time = date("Y-m-d 23:59:59",strtotime(substr($time,-10)));
            $obj = $obj->whereBetween('create_time',[$start_time,$end_time]);
        }
        //升降排序
        if(Input::has('type') && Input::has('code')) {
            if($code == 0) {
                $obj = $obj->orderBy($type,'asc');
            }
            if($code == 1) {
                $obj = $obj->orderBy($type,'desc');
            }
        }
        $field = Article::getField();
        $data = $obj->orderby('rank','desc')->orderby('create_time','desc')->paginate(10);
        return view('manage.article.index',compact('data','field','check_time','category','keyword','time','code','type'));
    }

    /**
     * 载入添加页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create() {
        #判断权限
        if($this->rule['add'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $cate = ArticleCategory::where('status',1)->get();
        return view('manage.article.create',compact('cate'));
    }

    /**
     * 添加数据
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request) {
        #判断权限
        if($this->rule['add'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $savePath  = null;
        $input = $request->only('user_id','rank','name','category','title','keyword','description','picture','content');
        $rule = [
            'category' => 'required',
            'title' => 'required',
            'content' => 'required',
            'rank' => 'required',
            'keyword' => 'required',
            'description' => 'required'
        ];
        $message = [
            'required' => ':attribute 不能为空'
        ];
        $attributes = [
            'category' => '分类',
            'title' => '标题',
            'content' => '内容',
            'rank' => '权重',
            'keyword' => '关键字',
            'description' => '描述'
        ];
//        dd($input);
        $validator = Validator::make($input, $rule, $message, $attributes);
        if($validator->fails()) {
            $warnings = $validator->messages()->first();
            return redirect()->back()->withInput()->withErrors($warnings);
        }
        else {
            if(Article::whereName($input['name'])->first()) {
                return redirect()->back()->withInput()->withErrors('文章名称已经存在');
            }
            else {
                if($request->hasFile('picture')) {
                    $file = $request->file('picture');
//                    dd($file);
                    if(!$file->isValid()) {
                        return redirect()->back()->withInput()->withErrors('上传文件有误！');
                    }
                    $newFileName = md5(time().rand(0,10000)) . '.' . $file->getClientOriginalExtension();

                    $destinationPath = 'file/'.date('Y-m-d');  //public文件夹下新建storage/uploads文件夹
                    $file->move($destinationPath,$newFileName);
                    $savePath = date('Y-m-d') . '/' . $newFileName;
                }

                if(Article::insert([
                    'rank' => $input['rank'],
                    'create_user' => $input['user_id'],
                    'name' => $input['name'],
                    'category_id' =>$input['category'],
                    'title' => $input['title'],
                    'keyword' => $input['keyword'],
                    'picture' => $savePath,
                    'description' => $input['description'],
                    'content' => $input['content']
                ])) {
                    return Redirect::to("manage/article");
                }
                else  {
                    return redirect()->back()->withInput()->withErrors('添加失败');
                }
            }
        }
    }

    /**
     *获取更新数据
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id) {
        #判断权限
        if($this->rule['update'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $cate = ArticleCategory::where('status',1)->get();
        $article = Article::where('id',$id)->first();
        return view('manage.article.edit',compact('cate','article'));
    }

    /**
     * 更新数据
     * @param Request $request
     * @param $id
     * @return mixed
     */
    public function update(Request $request,$id) {
        #判断权限
        if($this->rule['update'] == 0){
            return redirect()->back()->withInput()->withErrors('权限不足！');
        }
        $savePath  = null;
        $input = $request->only('user_id','rank','name','category','title','keyword','description','picture','content');
        $rule = [
            'category' => 'required',
            'title' => 'required',
            'content' => 'required',
            'rank' => 'required',
            'keyword' => 'required',
            'description' => 'required'
        ];
        $message = [
            'required' => ':attribute 不能为空'
        ];
        $attributes = [
            'category' => '分类',
            'title' => '标题',
            'content' => '内容',
            'rank' => '权重',
            'keyword' => '关键字',
            'description' => '描述'
        ];
//        dd($input);
        $validator = Validator::make($input, $rule, $message, $attributes);
        if($validator->fails()) {
            $warnings = $validator->messages()->first();
            return redirect()->back()->withInput()->withErrors($warnings);
        }
        else {
            if(Article::whereName($input['name'])->where('id','!=',$id)->first()) {
                return redirect()->back()->withInput()->withErrors('文章名称已经存在');
            }
            else {
                if($request->hasFile('picture')) {
                    $file = $request->file('picture');
//                    dd($file);
                    if(!$file->isValid()) {
                        return redirect()->back()->withInput()->withErrors('上传文件有误！');
                    }
                    $newFileName = md5(time().rand(0,10000)) . '.' . $file->getClientOriginalExtension();

                    $destinationPath = 'file/'.date('Y-m-d');  //public文件夹下新建storage/uploads文件夹
                    $file->move($destinationPath,$newFileName);
                    $savePath = date('Y-m-d') . '/' . $newFileName;
                }
                else {
                    $savePath = Article::whereId($id)->pluck('picture')[0];
                }
                if(Article::where('id',$id)->update([
                    'rank' => $input['rank'],
                    'update_user' => $input['user_id'],
                    'name' => $input['name'],
                    'category_id' =>$input['category'],
                    'title' => $input['title'],
                    'keyword' => $input['keyword'],
                    'picture' => $savePath,
                    'description' => $input['description'],
                    'content' => $input['content']
                ])) {
                    return Redirect::to("manage/article");
                }
                else  {
                    return redirect()->back()->withInput()->withErrors('更新失败');
                }
            }
        }
    }

    /**
     * 修改分类状态
     * @return array
     */
    public function status()
    {
        #判断权限
        if($this->rule['update'] == 0){
            return [
                'code' => 101,
                'msg' => '权限不足！'
            ];
        }
        $id = Input::get('id');
        $status = Input::get('status');
        if($status == 1) {
            $del = Article::where('id',$id)->update(['status'=>1,'update_user'=>session('user.id')]);
            $msg = '启用成功！';
        }else{
            $del = Article::where('id',$id)->update(['status'=>0,'update_user'=>session('user.id')]);
            $msg = '禁用成功！';
        }
        if(!$del){
            return [
                'code'=>101,
                'msg'=>'设置失败！'
            ];
        }
        return [
            'code'=>100,
            'msg'=>$msg
        ];
    }

    /**
     * 删除数据
     * @param $id
     * @return array
     */
    public function destroy() {
        #判断权限
        if($this->rule['delete'] == 0){
            return [
                'code' => 101,
                'msg' => '权限不足！'
            ];
        }
        $id = Input::Get('id');
        $res = Article::where('id',$id)->delete();
        if($res){
            return [
                'code' => 100,
                'msg' => '删除成功！'
            ];
        }else{
            return [
                'code' => 101,
                'msg' => '删除失败！'
            ];
        }
    }
}
